import { InjectionKey, ref, SetupContext } from "vue"
import { FormTableEmits, FormTableProps } from "./form-table"
import { useCssStyle } from "@ui/utils/css"
import { TableInstance } from 'element-plus'
import { EventChange } from "@ui/utils/var/event"
export const provideFormTableId: InjectionKey<(name: string, index: number, v: any) => void> = Symbol('form-table')
export const useFormTable = (props: FormTableProps, emit: SetupContext<FormTableEmits>['emit']): any => {
  const _ref = ref<TableInstance>(), _class = ref<any>({ 'z-form-table': true }), _style = ref<any>({})
  let height: number = 0
  watch(() => ({ basis: props.basis, auto: props.auto }), ({ basis, auto }) => {
    if (basis || auto) {
      _style.value.flexBasis = useCssStyle(basis || '0')
      _style.value.flexGrow = basis ? 0 : auto
      _style.value.overflow = 'auto'
    }
  }, { immediate: true })
  function layout() {
    if (_ref.value) {
      const v = _ref.value.$el.clientHeight
      if (height != v) {
        height = v
        _style.value.height = v + 'px'
      }
    }
  }
  watch(() => props.data, () => {
    _style.value.height = undefined
  }, { immediate: true })
  onMounted(() => {
    layout()
  })
  function change(name: string, index: number, v: any) {
    emit(EventChange, { name, index, v })
  }
  provide(provideFormTableId, change)
  return {
    _ref,
    _class,
    _style,
    layout
  }
}